package com.angel.web.app;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.angel.core.Constants;
import com.angel.core.base.JsonEntity;
import com.angel.core.util.CodeUtil;
import com.angel.core.util.FileUpload;
import com.angel.core.util.JsonUtil;
import com.angel.health.BuzExamination;
import com.angel.provider.app.BuzMachineProvider;
import com.angel.provider.health.BuzExaminationProvider;
import com.github.pagehelper.StringUtil;

/**
 * @author 作者姓名 cheng
 * @version 创建时间：2016年9月23日 下午2:10:18 类说明 体检报告
 */
@Controller
@RequestMapping("app/examination")
public class AppExaminationController {

	@Autowired
	private BuzExaminationProvider exaService;
	
	@Autowired
	private BuzMachineProvider bmProvider;
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	/**
	 * 上传健康报告
	 * 
	 * @param buzExamination
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "upload", produces = "application/json; charset=UTF-8")
	public String uploadExamination(BuzExamination buzExamination, MultipartHttpServletRequest request) {
		MultiValueMap<String, MultipartFile> multiFileMap = request.getMultiFileMap();
		String uploadUrl;
		try {
			uploadUrl = FileUpload.uploadForFastdfs(multiFileMap);
			buzExamination.setUploadUrl(uploadUrl);
			int insert = exaService.insert(buzExamination);
			buzExamination.setCode(CodeUtil.createCode(null, Constants.EXAMINATION, buzExamination.getId()));
			exaService.updateById(buzExamination);
			if (insert > 0) {
				return JsonUtil.toJson(new JsonEntity("200", buzExamination));
			} else {
				return JsonUtil.toJson(new JsonEntity("-1", "失败"));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return JsonUtil.toJson(new JsonEntity("-1", "失败"));
		}
	}

	/**
	 * 删除体检报告
	 * @param buzExamination
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "del", produces = "application/json; charset=UTF-8")
	public String del(BuzExamination buzExamination) {
		int delById = exaService.delAll(buzExamination.getId().toString());
		if (delById > 0) {
			return JsonUtil.toJson(new JsonEntity("200", buzExamination));
		} else {
			return JsonUtil.toJson(new JsonEntity("-1", "失败"));
		}
	}

	/**
	 * 编辑体检报告
	 * 
	 * @param buzExamination
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "edit", produces = "application/json; charset=UTF-8")
	public String editExamination(BuzExamination buzExamination, MultipartHttpServletRequest request) {
		if (buzExamination.getId() == 0 || buzExamination.getId() == null) {
			return JsonUtil.toJson(new JsonEntity("-1", "参数不正确！"));
		}
		MultiValueMap<String, MultipartFile> multiFileMap = request.getMultiFileMap();
		String uploadUrl;
		try {
			uploadUrl = FileUpload.uploadForFastdfs(multiFileMap);
			buzExamination.setUploadUrl(uploadUrl);
			int updateById = exaService.updateById(buzExamination);
			if (updateById > 0) {
				return JsonUtil.toJson(new JsonEntity("200", buzExamination));
			} else {
				return JsonUtil.toJson(new JsonEntity("-1", "失败"));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return JsonUtil.toJson(new JsonEntity("-1", "失败"));
		}
	}

	/**
	 * 查看所有健康报告
	 * 
	 * @param buzExamination
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "index", produces = "application/json; charset=UTF-8")
	public String index(BuzExamination buzExamination) {
		buzExamination.setEnable(1);
		List<Map<String, Object>> list = exaService.findAll(buzExamination);
		return JsonUtil.toJson(new JsonEntity("200", list));
	}

	/**
	 * 一体机接入体检报告
	 * @param json
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "adForMachine", produces = "application/json; charset=UTF-8")
	public synchronized String adForMachine(HttpServletResponse response,HttpServletRequest request){
//		String result = "";
//		response.setContentType("text/html");
//        java.io.BufferedReader reader = null;  
//        try {  
//            reader = request.getReader();// 获得字符流  
//            StringBuffer content = new StringBuffer();  
//            String line;  
//            while ((line = reader.readLine()) != null) {  
//                content.append(line + "\r\n");  
//            }  
//            result = content.toString();  
//        } catch (Exception e) {  
//            e.printStackTrace();  
//        } finally {  
//            try {  
//                reader.close();  
//                reader = null;  
//            } catch (Exception e) {  
//  
//            }  
//        }
        
        ServletInputStream inputStream = null;
        String _result = "";
        try {
			inputStream = request.getInputStream();
			_result = IOUtils.toString(inputStream);
		} catch (IOException e) {
			// TODO Auto-generated catch block
		}finally{
			IOUtils.closeQuietly(inputStream);
		}
        Map<String,String> map = new HashMap<String,String>();
        map.put("success", "true");
        map.put("message", "success");
        if(!StringUtil.isEmpty(_result)){
        	bmProvider.readMachine(_result);
        	System.err.println(_result+"-------------------");
        }
		return JsonUtil.toJson(map);
	}
}
